﻿using LeShiTao_Library.WeChat.Public_WC;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace TB_WS.WeChat._59igou
{
    public partial class Default : System.Web.UI.Page
    {
        const string Token = "dkp921123";
        private static string XML_Path;
        private static SysInfo si;
        protected void Page_Load(object sender, EventArgs e)
        {
            //初始化XML路径以及SysInfo
            XML_Path= Request.PhysicalApplicationPath.ToString() + "wechat\\59igou\\59igou.xml";
            si = new SysInfo(XML_Path);

            HttpContext.Current.Request.Url.Host.ToString();
            string postStr = "";
            if (Request.HttpMethod.ToLower() == "get")
            {
                Valid();
            }
            else if (Request.HttpMethod.ToLower() == "post")
            {
                Stream s = System.Web.HttpContext.Current.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                postStr = Encoding.UTF8.GetString(b);
                if (!string.IsNullOrEmpty(postStr))
                {
                    ResponseMsg(postStr);
                }
            }
        }
        private static string Get_WXR_Str()
        {
            int Seller_ID = Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString());
            DataSet WXR_DST = Class.WX_Reply.get_WXR_Info(Seller_ID, "WX_Reply_Low");
            if (WXR_DST.Tables[0].Rows.Count == 0)
            {
                return "";
            }
            else
            {
                return WXR_DST.Tables[0].Rows[0][3].ToString();
            }
        }
        private void ResponseMsg(string weixinXML)
        {
           
            Message_Handle MH = new Message_Handle(weixinXML);
            string ToUserName = MH.GET_ToUserName();
            string FromUserName = MH.GET_FromUserName();
            string MsgType = MH.GET_MsgType();
            string MsgInfo = null;
            string EventKey = null;
            int Seller_ID= Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString());
            if (MsgType == "event")
            {
                
                string Event = MH.GET_Event().Trim().ToString();
                
                if (Event== "subscribe")
                {
                    Class.Unit.INSERT_LOG(weixinXML);
                    //未关注扫描
                    EventKey = MH.GET_EventKey().Trim().ToString().Split('_')[1].ToString();
                }
                else if(Event== "SCAN")
                {
                    Class.Unit.INSERT_LOG(weixinXML);
                    EventKey = MH.GET_EventKey().Trim().ToString();
                }
                else
                {
                    EventKey = "";
                }
                if(EventKey!="")
                {

                    string Resp_Str = "";
                    WS_HongBao.HongBao_Logic AHL = new WS_HongBao.HongBao_Logic();
                    //获取QR码的详细参数
                    DataSet QR_DST = Class.HongBao_Logic.get_QR_scene_info(EventKey);
                    //获取红包状态
                    string QR_Type = QR_DST.Tables[0].Rows[0][8].ToString();
                    
                    if (QR_Type == "Wait_Collect")
                    {
                        //赋值金额
                        int Money = Convert.ToInt32(QR_DST.Tables[0].Rows[0][6].ToString());
                        //获取订单号
                        string Tids = QR_DST.Tables[0].Rows[0][4].ToString();//载入Tids

                        
                        Class.Top_Logic TL = new Class.Top_Logic(si.GET_Seller_Nick());

                       
                        //获取订单号的状态是否支持返现
                        string[] Rate_State = TL.GET_Rate_State_New(Tids,si.GET_WX_User().ToString()).Split('#');
                        

                        if (Convert.ToInt32(Rate_State[0]) == 0)
                        {
                            //正常返现
                            int Collect_Type = AHL.Check_HongBao(EventKey);
                            if (Collect_Type == -1)
                            {
                                Resp_Str = "订单号：" + Tids + " 的红包已发放过啦，不能重复领取喔~\n\n"+Get_WXR_Str();
                            }
                            else
                            {
                                string mch_billno = HongBao.get_mch_billno();
                                string result = si.HB.PostPage(si.HB.SET_REQUEST(FromUserName, mch_billno, Money));
                                Class.Unit.INSERT_LOG(result);
                                WX_Pay WP = new WX_Pay(result);
                                if (WP.Pay_RT_result_code()== "SUCCESS"&&WP.Pay_RT_Msg()=="发放成功")
                                {
                                    //发放成功
                                    User_Manage UM = new User_Manage(WP.Pay_RT_re_openid().ToString(), si.GET_WX_User());
                                    //写入红包发放记录
                                    Class.HB_Log.insert_Get_HB_Log(Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString()),
                                        EventKey, WP.Pay_RT_re_openid(), UM.Return_nickname(),
                                        WP.Pay_RT_mch_billno(), LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP().ToString(), result);
                                    AHL.COLLECT_HONGBAO(EventKey);//设置红包领取状态
                                    Resp_Str = "亲爱的：" + UM.Return_nickname().ToString() + "  红包已到账 请拆红包\n\n"+Get_WXR_Str();
                                   
                                }
                                else if(WP.Pay_RT_err_code()== "PROCESSING")
                                {
                                    User_Manage UM = new User_Manage(WP.Pay_RT_re_openid().ToString(), si.GET_WX_User());
                                    //写入红包发放记录
                                    Class.HB_Log.insert_Get_HB_Log(Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString()),
                                        EventKey, WP.Pay_RT_re_openid(), UM.Return_nickname(),
                                        WP.Pay_RT_mch_billno(), LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP().ToString(), result);
                                    AHL.COLLECT_HONGBAO(EventKey);//设置红包领取状态
                                    Resp_Str = "亲爱的：" + UM.Return_nickname().ToString() + "  很抱歉 红包领取的路上有点堵车，大红包马上到达~ 请等候，如10分钟还未收到 请截图联系我们客服即可~\n\n" + Get_WXR_Str();
                                }
                                else
                                {
                                    //发放失败
                                    Resp_Str = "返现失败  请截图并联系我们客服 谢谢您 失败原因：" + WP.Pay_RT_err_code_des().ToString()+"\n\n" + Get_WXR_Str();
                                }
                                
                            }
                        }

                        else
                        {
                            Resp_Str = "很抱歉 亲 返现失败\n\n原因是：\n" +
                                Rate_State[1].ToString()+"\n\n" + Get_WXR_Str();
                        }
                    }
                    else if(QR_Type == "Collected")
                    {
                        Resp_Str = "亲 红包已经领取过了喔~ 无法重复领取红包的喔~ 如果有异常或有需要咨询的 可以直接回复，我们会尽快回复您~\n\n" + Get_WXR_Str();
                    }
                    else if(QR_Type=="End")
                    {
                        Resp_Str = "亲 该红包已作废，详情请联系我们客服喔~ 或直接回复我们\n\n" + Get_WXR_Str();
                    }
                    else if (QR_Type == "Wait_Collect_Rate_2")
                    {
                        //赋值金额
                        int Money = Convert.ToInt32(QR_DST.Tables[0].Rows[0][6].ToString());
                        //获取订单号
                        string Tids = QR_DST.Tables[0].Rows[0][4].ToString();//载入Tids


                        Class.Top_Logic TL = new Class.Top_Logic(si.GET_Seller_Nick());


                        //获取订单号的状态是否支持返现
                        string[] Rate_State = TL.GET_Rate_State_Appened_Rate_2(Tids,si.GET_WX_User().ToString()).Split('#');


                        if (Convert.ToInt32(Rate_State[0]) == 0)
                        {
                            //正常返现
                            int Collect_Type = AHL.Check_HongBao(EventKey);
                            if (Collect_Type == -1)
                            {
                                Resp_Str = "订单号：" + Tids + " 的红包已发放过啦，不能重复领取喔~\n\n" + Get_WXR_Str();
                            }
                            else
                            {
                                string mch_billno = HongBao.get_mch_billno();
                                string result = si.HB.PostPage(si.HB.SET_REQUEST(FromUserName, mch_billno, Money));
                                Class.Unit.INSERT_LOG(result);
                                WX_Pay WP = new WX_Pay(result);
                                if (WP.Pay_RT_result_code() == "SUCCESS" && WP.Pay_RT_Msg() == "发放成功")
                                {
                                    //发放成功
                                    User_Manage UM = new User_Manage(WP.Pay_RT_re_openid().ToString(), si.GET_WX_User());
                                    //写入红包发放记录
                                    Class.HB_Log.insert_Get_HB_Log(Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString()),
                                        EventKey, WP.Pay_RT_re_openid(), UM.Return_nickname(),
                                        WP.Pay_RT_mch_billno(), LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP().ToString(), result);
                                    AHL.COLLECT_HONGBAO(EventKey);//设置红包领取状态
                                    Resp_Str = "亲爱的：" + UM.Return_nickname().ToString() + "  红包已到账 请拆红包\n\n" + Get_WXR_Str();

                                }
                                else if (WP.Pay_RT_err_code() == "PROCESSING")
                                {
                                    User_Manage UM = new User_Manage(WP.Pay_RT_re_openid().ToString(), si.GET_WX_User());
                                    //写入红包发放记录
                                    Class.HB_Log.insert_Get_HB_Log(Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString()),
                                        EventKey, WP.Pay_RT_re_openid(), UM.Return_nickname(),
                                        WP.Pay_RT_mch_billno(), LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP().ToString(), result);
                                    AHL.COLLECT_HONGBAO(EventKey);//设置红包领取状态
                                    Resp_Str = "亲爱的：" + UM.Return_nickname().ToString() + "  很抱歉 红包领取的路上有点堵车，大红包马上到达~ 请等候，如10分钟还未收到 请截图联系我们客服即可~\n\n" + Get_WXR_Str();
                                }
                                else
                                {
                                    //发放失败
                                    Resp_Str = "返现失败  请截图并联系我们客服 谢谢您 失败原因：" + WP.Pay_RT_err_code_des().ToString()+"\n\n" + Get_WXR_Str();
                                }

                            }
                        }

                        else
                        {
                            Resp_Str = "很抱歉 亲 返现失败\n\n原因是：\n" +
                                Rate_State[1].ToString() + "\n\n" + Get_WXR_Str();
                        }
                    }
                    else if(QR_Type== "UN_Collect")
                    {
                        //无条件发放红包
                        int Money = Convert.ToInt32(QR_DST.Tables[0].Rows[0][6].ToString());
                        int Collect_Type = AHL.Check_HongBao(EventKey);
                        string mch_billno = HongBao.get_mch_billno();
                        string result = si.HB.PostPage(si.HB.SET_REQUEST(FromUserName, mch_billno, Money));
                        Class.Unit.INSERT_LOG(result);
                        WX_Pay WP = new WX_Pay(result);
                        if (WP.Pay_RT_result_code() == "SUCCESS" && WP.Pay_RT_Msg() == "发放成功")
                        {
                            //发放成功
                            User_Manage UM = new User_Manage(WP.Pay_RT_re_openid().ToString(), si.GET_WX_User());
                            //写入红包发放记录
                            Class.HB_Log.insert_Get_HB_Log(Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString()),
                                EventKey, WP.Pay_RT_re_openid(), UM.Return_nickname(),
                                WP.Pay_RT_mch_billno(), LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP().ToString(), result);

                            AHL.COLLECT_HONGBAO(EventKey);//设置红包领取状态
                            Resp_Str = "亲爱的：" + UM.Return_nickname().ToString() + "  红包已到账 请拆红包\n\n" + Get_WXR_Str();

                        }
                        else if (WP.Pay_RT_err_code() == "PROCESSING")
                        {
                            //发放成功
                            User_Manage UM = new User_Manage(WP.Pay_RT_re_openid().ToString(), si.GET_WX_User());
                            //写入红包发放记录
                            Class.HB_Log.insert_Get_HB_Log(Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString()),
                                EventKey, WP.Pay_RT_re_openid(), UM.Return_nickname(),
                                WP.Pay_RT_mch_billno(), LeShiTao_Library.Tools.Data_Handle.GET_UNIX_TIMESTAMP().ToString(), result);
                            AHL.COLLECT_HONGBAO(EventKey);//设置红包领取状态

                            Resp_Str = "亲爱的：" + UM.Return_nickname().ToString() + "  很抱歉 红包领取的路上有点堵车，大红包马上到达~ 请等候，如10分钟还未收到 请截图联系我们客服即可~\n\n" + Get_WXR_Str();
                        }
                        else
                        {
                            //发放失败
                            Resp_Str = "返现失败  请截图并联系我们客服 谢谢您 失败原因：" + WP.Pay_RT_err_code_des().ToString() + "\n\n" + Get_WXR_Str();
                        }
                        
                    }
                    else if(QR_Type=="Express_Push")
                    {
                        //扫描到订单推送
                        string Tids = QR_DST.Tables[0].Rows[0][4].ToString();//载入Tids
                        int Tid_Count_Push = Class.Express_Push.get_Push_tid_count(Seller_ID, Tids);
                        if(Tid_Count_Push==0)
                        {
                            //还没有加入推送列表
                            Class.Express_Push.Insert_Push_Tid(Seller_ID, Tids, FromUserName);
                            Resp_Str="亲 您的订单号："+Tids+" 的订单我们已经记录下来了喔~ 接下来的时间，我们会把最新的物流信息推送给您，如果您不需要我们告诉您物流信息，请回复：我不要物流信息   即可关闭推送喔~" + "\n\n" + Get_WXR_Str();
                        }
                        else
                        {
                            //加入了推送列表
                            Resp_Str="亲 您已扫描过这个二维码了，静候我们为您推送物流信息喔~ 可能会比官网直接查询物流信息略微延迟几分钟，不会太久的哈~" + "\n\n" + Get_WXR_Str();
                        }
                    }
                    Response.Write(SendMessage.SendTXTMessage(Resp_Str, FromUserName, ToUserName));
                }
                else
                {
                    //Response.Write(SendMessage.SendTXTMessage("红包异常 请联系我们 或截图直接回复", FromUserName, ToUserName));
                }
                
            }
            else
            {
                MsgInfo = MH.GET_Content();
            }
            try
            {
                if (MsgType == "text")
                {
                    if (MsgInfo == "我")
                    {
                        Response.Write(SendMessage.SendTXTMessage(FromUserName, FromUserName, ToUserName));
                    }
                    else if (MsgInfo == "PJ")
                    {
                        LeShiTao_Library.WeChat.Public_WC.Template_Message TM =
                            new Template_Message(si.GET_WX_User());
                        string RT = TM.TM_Get_Rate_Message(si.GET_WX_User(), FromUserName, "中差评提醒", "25443342124324532", "评价类型：差评请关注处理", Class.Template_Manage.get_Temp_ID(si.GET_WX_User(), "OPENTM205102209").ToString());
                        Response.Write("");
                    }
                    else if (MsgInfo.Split('#')[0] == "HBC")
                    {
                        try {
                            //string result = si.HB.PostPage(si.HB.SET_REQUEST(FromUserName, mch_billno, Money));
                            string FK = si.HBC.PostPage(si.HBC.SET_REQUEST(MsgInfo.Split('#')[1].ToString()));
                            Response.Write(SendMessage.SendTXTMessage(FK, FromUserName, ToUserName));
                        }
                        catch (Exception ex)
                        {
                            Response.Write(SendMessage.SendTXTMessage(ex.Message.ToString(), FromUserName, ToUserName));
                        }
                    }
                    else if (MsgInfo == "监听评价")
                    {
                        //int Seller_ID = Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString());
                        int WX_User_Count = Class.WX_User_ID.Get_WX_User_Count(Seller_ID, FromUserName);
                        if (WX_User_Count == 0)
                        {
                            //开始增加
                            Class.WX_User_ID.Insert_WX_User(Seller_ID, FromUserName);
                            Response.Write(SendMessage.SendTXTMessage("欢迎加入：" + si.GET_Seller_Nick().ToString() + " 评价监听列表 接下来 顾客在扫描二维码后如若评价为中差评，我将会在此通知到您  退订请回复：退出监听评价", FromUserName, ToUserName));
                        }
                        else
                        {
                            //已增加
                            Response.Write(SendMessage.SendTXTMessage("您已加入过：" + si.GET_Seller_Nick().ToString() + " 评价监听列表", FromUserName, ToUserName));
                        }
                    }
                    else if (MsgInfo == "退出监听评价")
                    {
                        //int Seller_ID = Convert.ToInt32(Class.Seller_Manage.select_Seller_Info(si.GET_Seller_Nick()).Tables[0].Rows[0][0].ToString());
                        Class.WX_User_ID.Delete_WX_User(Seller_ID, FromUserName);
                        Response.Write(SendMessage.SendTXTMessage("您已退出：" + si.GET_Seller_Nick().ToString() + " 评价监听列表 我将不会再通知您中差评事宜", FromUserName, ToUserName));
                    }
                    else if (MsgInfo == "我不要物流信息")
                    {
                        Class.Express_Push.Delete_WX_ID_Push(FromUserName);
                        Response.Write(SendMessage.SendTXTMessage("亲 您已取消物流信息推送，如有需要推送，再次扫描二维码即可喔~" + "\n\n" + Get_WXR_Str(), FromUserName, ToUserName));
                    }
                    //if(MsgInfo.Length==16)
                    //{
                    //    //淘宝订单号
                    //    Class.Top_Logic CTL = new Class.Top_Logic("我就爱购数码专营店");
                    //    int State = CTL.GET_Booking_HB_State(MsgInfo);
                    //    if(State==-1)
                    //    {
                    //        Response.Write(SendMessage.SendTXTMessage("订单号："+MsgInfo+" 不在我们的订单数据库中，请检查订单号是否正确", FromUserName, ToUserName));
                    //    }
                    //    else if(State==-1)
                    //    {
                    //        Response.Write(SendMessage.SendTXTMessage("订单号：" + MsgInfo + " 的淘宝ID已经领取过红包啦~一个ID只能领取一个喔~", FromUserName, ToUserName));
                    //    }
                    //    else if(State==-2)
                    //    {
                    //        Response.Write(SendMessage.SendTXTMessage("订单号：" + MsgInfo + " 的订单状态不为：买家已付款，请检查订单状态喔，或联系我们客服", FromUserName, ToUserName));
                    //    }
                    //    else
                    //    {
                    //        //开始返现
                    //        WS_HongBao.HongBao_Logic AHL = new WS_HongBao.HongBao_Logic();
                    //        Random rd = new Random();
                    //        int Money = rd.Next(700, 1500);
                    //        string mch_billno = HongBao.get_mch_billno();
                    //        SysInfo si = new SysInfo(Request.PhysicalApplicationPath.ToString() + "wechat\\59igou\\59igou.xml");
                    //        si.HB.PostPage(si.HB.SET_REQUEST(FromUserName, mch_billno, Money));
                    //        //Class.Booking_HB.Insert_Booking(MsgInfo,)
                    //        Response.Write(SendMessage.SendTXTMessage("订单号：" + MsgInfo + " 红包发放成功，祝您购物愉快，请拆红包", FromUserName, ToUserName));
                    //    }
                    //}
                }
                else if (MsgType == "event")
                {
                    //Response.Write(SendMessage.SendTXTMessage("进入了事件", FromUserName, ToUserName));
                    if (EventKey == "Create_AS")
                    {
                        //创建售后信息
                    }
                    else if (EventKey == "Check_AS")
                    {
                        //查询售后信息
                    }
                }
                else
                {
                    Response.Write(SendMessage.SendTXTMessage(MH.GET_MsgType().ToString(), FromUserName, ToUserName));
                }
            }
            catch (Exception ex)
            {
                Response.Write(SendMessage.SendTXTMessage(ex.Message.ToString(), FromUserName, ToUserName));
            }
        }
        private void Valid()//检验用户
        {
            string echoStr = Request.QueryString["echoStr"].ToString();
            if (CheckSignature())
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    Response.Write(echoStr);
                    Response.End();
                }
            }
        }

        private bool CheckSignature()
        {
            string signature = Request.QueryString["signature"].ToString();
            string timestamp = Request.QueryString["timestamp"].ToString();
            string nonce = Request.QueryString["nonce"].ToString();
            string[] ArrTmp = { Token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr.Equals(signature))
            {
                return true;
            }
            else
            {
                return false;
            }
        }//签名校验
    }
}